package com.haha.gulimall.product.service.impl;

import cn.hutool.core.lang.TypeReference;
import com.haha.common.constant.ProductConstant;
import com.haha.common.to.SkuHasStockVo;
import com.haha.common.to.SkuReductionTo;
import com.haha.common.to.SpuBoundsTo;
import com.haha.common.to.es.SkuEsModel;
import com.haha.common.utils.R;
import com.haha.gulimall.product.dao.*;
import com.haha.gulimall.product.entity.*;
import com.haha.gulimall.product.feign.CouponFeignService;
import com.haha.gulimall.product.feign.SearchFeignService;
import com.haha.gulimall.product.feign.WareFeignService;
import com.haha.gulimall.product.service.SpuImagesService;
import com.haha.gulimall.product.vo.BaseAttrs;
import com.haha.gulimall.product.vo.Images;
import com.haha.gulimall.product.vo.Skus;
import com.haha.gulimall.product.vo.SpuSaveVo;
import com.sun.webkit.dom.AttrImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haha.common.utils.PageUtils;
import com.haha.common.utils.Query;

import com.haha.gulimall.product.service.SpuInfoService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    SpuInfoDescDao spuInfoDescDao;
    @Resource
    SpuImagesService spuImagesService;
    @Resource
    SkuInfoDao skuInfoDao;
    @Resource
    AttrDao attrDao;
    @Resource
    ProductAttrValueServiceImpl productAttrValueService;
    @Resource
    SkuImagesServiceImpl skuImagesServicel;
    @Resource
    SkuSaleAttrValueServiceImpl skuSaleAttrValueService;
    @Resource
    CouponFeignService couponFeignService;
    @Resource
    BrandDao brandDao;
    @Resource
    CategoryDao categoryDao;
    @Resource
    AttrServiceImpl attrService;
    @Resource
    WareFeignService wareFeignService;
    @Resource
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuSaveVo(SpuSaveVo spuSaveVo) {
        //1、保存spu基本信息pms_spu_info
        SpuInfoEntity spuInfo = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfo);
        spuInfo.setCreateTime(new Date());
        spuInfo.setUpdateTime(new Date());
        this.save(spuInfo);
        //2、保存Spu的描述图片 pms_spu_info_desc1
        SpuInfoDescEntity spuInfoDesc = new SpuInfoDescEntity();
        spuInfoDesc.setSpuId(spuInfo.getId());
        List<String> decript = spuSaveVo.getDecript();
        spuInfoDesc.setDecript(String.join(",", decript));
        spuInfoDescDao.insert(spuInfoDesc);
        //3、保存spu的图片集 pms_spu_images
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuInfo.getId(), images);
        //4、保存spu的规格参数； pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValue = new ProductAttrValueEntity();
            productAttrValue.setAttrId(attr.getAttrId());
            productAttrValue.setSpuId(spuInfo.getId());
            productAttrValue.setAttrName(attrDao.selectById(attr.getAttrId()).getAttrName());
            productAttrValue.setAttrValue(attr.getAttrValues());
            productAttrValue.setQuickShow(attr.getShowDesc());
            return productAttrValue;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(collect);
        //5、保存spu的积分信息; gulimall_sms->sms_spu_bounds
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(spuSaveVo.getBounds(),spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfo.getId());
        R r1 = couponFeignService.saveSpuBounds(spuBoundsTo);
        if(r1.getCode()!=0) log.error("远程保存sku积分信息失败");
        //5、保存当前spu对应的所有sku信息；

        //5.1) 、sku的基本信息; pms_sku_info
        List<Skus> skus = spuSaveVo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(obj -> {
                List<Images> images1 = obj.getImages();
                String defaultImags = "";
                for (Images i : images1) {
                    if (i.getDefaultImg() == 1) {
                        defaultImags = i.getImgUrl();
                    }
                }

                SkuInfoEntity skuInfo = new SkuInfoEntity();
                BeanUtils.copyProperties(obj, skuInfo);
                skuInfo.setBrandId(spuSaveVo.getBrandId());
                skuInfo.setCatalogId(spuSaveVo.getCatalogId());
                skuInfo.setSpuId(spuInfo.getId());
                skuInfo.setSkuDefaultImg(defaultImags);
                skuInfo.setSaleCount(0L);
                skuInfoDao.insert(skuInfo);
                Long skuId = skuInfo.getSkuId();
                // 5.2) 、sku的图片信息; pms_sku_images
                List<SkuImagesEntity> skuImagesEntitys = images1.stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(image->{
                    return !StringUtils.isEmpty(image.getImgUrl());
                        }).collect(Collectors.toList());
                //todo 没有图片路径的不用
                skuImagesServicel.saveBatch(skuImagesEntitys);
                //5.3） 、sku的销售属性信息： pms_sku_sale_attr_value
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = obj.getAttr().stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValue = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValue);
                    skuSaleAttrValue.setSkuId(skuId);
                    return skuSaleAttrValue;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                //5.4) 、sku的优惠、满减,会员相关等信息; gulimall_sms->sms_sku_Ladder(sms_sku_full_reduction(s
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(obj,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if(skuReductionTo.getFullCount()>0 || skuReductionTo.getFullPrice().signum()==1){
                    R r = couponFeignService.saveSkuReduction(skuReductionTo);
                    if(r.getCode()!=0) log.error("远程保存优惠信息失败");
                }

            });
        }

         }

    @Override
    public PageUtils queryPageCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> qw = new QueryWrapper<>();
        String key = (String) params.get("key");
        qw.and(StringUtils.isNotEmpty(key),wrapper->{
            wrapper.or().eq("id",key)
                    .or().like("spu_name",key)
                    .or().like("spu_description",key);
        });
        String brandId = (String) params.get("brandId");
        String catelogId = (String) params.get("catelogId");
        String status = (String) params.get("status");
        qw.eq(StringUtils.isNotEmpty(brandId)&& !"0".equals(brandId),"brand_id",brandId)
                .eq(StringUtils.isNotEmpty(catelogId)&&!"0".equals(catelogId),"catalog_id",catelogId)
                .eq(StringUtils.isNotEmpty(status),"publish_status",status);

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),qw

        );

        return new PageUtils(page);
    }

    @Override
    public void spuUp(Long spuId) {

        List<SkuInfoEntity> skus = skuInfoDao.selectList(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        List<Long> skuids = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        List<ProductAttrValueEntity> attrValueForSpu = productAttrValueService.attrValueForSpu(spuId); //这里面的属性id有可搜索与不可搜索

        List<Long> attrIds = attrValueForSpu.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        List<Long> searchAttrIds=attrService.selectSerarchAttrIds(attrIds);  //查找可以检索的属性
        Set<Long> haha = new HashSet<>(searchAttrIds);

        List<SkuEsModel.Attrs> collect = attrValueForSpu.stream().filter(item -> {
            return haha.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attr = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attr);
            return attr;
        }).collect(Collectors.toList());
        Map<Long, Boolean> stockMap = null;
        try {
            R skuHasStock = wareFeignService.getSkuHasStock(skuids);
            TypeReference<List<SkuHasStockVo>> listTypeReference = new TypeReference<List<SkuHasStockVo>>(){};
            stockMap = skuHasStock.getData(listTypeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        }
        catch (Exception e) {
            log.error("远程调用是否有库存出现失败，because：{}",e);
        }
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> skuEsModels = skus.stream().map(skuInfoEntity -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfoEntity, skuEsModel);
            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());
            BrandEntity brandEntity = brandDao.selectById(skuInfoEntity.getBrandId());
            CategoryEntity categoryEntity = categoryDao.selectById(skuInfoEntity.getCatalogId());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setCatalogName(categoryEntity.getName());
            skuEsModel.setAttrs(collect);
            skuEsModel.setHotScore(0L);
            if(finalStockMap == null){
                skuEsModel.setHasStock(true);
            }
            else{
                skuEsModel.setHasStock(finalStockMap.get(skuInfoEntity.getSkuId()));
            }
            return skuEsModel;
        }).collect(Collectors.toList());
        R r = searchFeignService.productSave(skuEsModels);
        if(r.getCode() == 0){
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.UP_SPU.getCode());
        }
        else{
            System.out.println("保存失败");
        }

    }

}